package com.hltx.controller.shopping;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.hltx.constants.CommonConstant;
import com.hltx.constants.GoodsConstant;
import com.hltx.controller.base.BaseController;
import com.hltx.pojo.goods.GoodsOrder;
import com.hltx.pojo.ratioconfigure.RatioConfigure;
import com.hltx.pojo.user.User;
import com.hltx.service.goods.GoodsManager;
import com.hltx.service.pay.PayManager;
import com.hltx.service.shopping.ShoppingManager;
import com.hltx.util.CustomUtil;
import com.hltx.util.DataUtil;
import com.hltx.util.DateUtil;
import com.hltx.util.ResultInfo;





/**
 * 购物车controller
 * 
 * @author shibeilei
 *
 */
@Controller
@RequestMapping("/shoppingCart")
public class ShoppingController extends BaseController{

	@Autowired
	private ShoppingManager shoppingManager;
	
	@Autowired
	private GoodsManager goodsService;
	
	@Autowired
	private PayManager payService;
	
	/**
	 * 打开购物车列表页
	 */
	@RequestMapping
	public String index() {
		return "shoppingCart/shoppingcart";
	}
	
	@RequestMapping(value = "/getList", method = { RequestMethod.POST})
	@ResponseBody
	public Map<String,Object> getList(HttpServletRequest request,HttpServletResponse response, 
			HttpSession session){
		this.logBefore(logger, "查询购物车列表");
		Map<String, Object> resMap = new HashMap<String, Object>();
		List<GoodsOrder> goodsN = new ArrayList<GoodsOrder>();
		try{
			User user = (User)session.getAttribute("sessionUser");
			RatioConfigure ratioConfigure = payService.getRatioConfigure();
			if(user != null){
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("userId", user.getId());
			params.put("curTime", DateUtil.getTime());
			
			List<GoodsOrder> goods = goodsService.getGoodsListByShopCart(params);
			goodOrderMethod(request, response, goodsN, user, params, goods);
			}else{
				String cookieValue=null;
				Cookie cookies[] =  request.getCookies();
				if(cookies.length>0){
					for (Cookie cookie : cookies) {
						if (cookie.getName().equals(CommonConstant.HLTX_SHOPCART_TICKET)) {
							cookieValue = cookie.getValue();
							break;
						}
					}
				}
				if (cookieValue!=null) {
					List<GoodsOrder> goods;
					String cookieValues[] = cookieValue.split("@");
					for (int i = 0; i < cookieValues.length; i++) {
						String values[] = cookieValues[i].split(":");
							if (values[0].trim().length()>0) {
							goods = goodsService.getGoodsListByGid(Integer.parseInt(values[0].trim()));
							goods.get(0).setId(Integer.parseInt(values[0].trim()));
							goods.get(0).setSpec((values[1]));
							goods.get(0).setBuyNum(Integer.parseInt(values[2]));
							Map<String, Object> params = new HashMap<String, Object>();
							params.put("curTime", DateUtil.getTime());
							goodOrderMethod(request, response, goodsN, user, params, goods);
							}
						
					}
				}
			}
			resMap.put("ratioConfigure", ratioConfigure);
			resMap.put("goodsList", goodsN);
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
			
		}catch(Exception e){
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);
		return resMap;
	}

	private void goodOrderMethod(HttpServletRequest request, HttpServletResponse response, List<GoodsOrder> goodsN,
			User user, Map<String, Object> params, List<GoodsOrder> goods) {
		//封装购物车
		for(GoodsOrder go : goods){
			if(StringUtils.equals(go.getState(), "00")){
				//移除购物车
				this.removeByGoods(go.getId(),go.getSpec(),user, request, response);
				continue;
			}
			//商品是否促销
			params.put("goodsId", go.getId());
			Map<String, Object> goodsSales = goodsService.getGoodsSalesByGId(params);
			if(goodsSales == null){
				go.setIsSales("00");
			}
			BigDecimal bidPrice = go.getBidPrice();
			BigDecimal price = go.getPrice();
			if("01".equals(go.getIsSales())){
				price = go.getRealPrice();
			}
			BigDecimal discount = bidPrice.multiply(DataUtil.getBigDecimal(10)).divide(go.getMarketPrice(), 2 , BigDecimal.ROUND_HALF_DOWN);
			RatioConfigure ratioConfigure = payService.getRatioConfigure();
			BigDecimal minRatio = ratioConfigure.getMinRatio();
			BigDecimal maxRatio = ratioConfigure.getMaxRatio();
			if(discount.compareTo(maxRatio) <= 0){
				int changePoints =0;
				BigDecimal changePrice = BigDecimal.ZERO;
				if (discount.compareTo(minRatio) == 1) {
					 changePoints = CustomUtil.requiredIntegral(DataUtil.getBigDecimal(price, 2), discount, minRatio);
					 changePrice = price.subtract(DataUtil.getBigDecimal(changePoints, 2));
				}else { 
					 changePoints = price.setScale(0, BigDecimal.ROUND_CEILING).intValue();
				}
				go.setChangePoints(changePoints);
				go.setChangePrice(changePrice);
			}
			go.setPrice(price);
			go.setReturnAmount(DataUtil.getBigDecimal(go.getReturnAmount()));
			//获取商品规格 
			Map<String, Object> goodsSpec = null;
			List<Map<String, Object>> goodsSpecPro = null;
			if(StringUtils.equals(go.getIsSelectSpec(), GoodsConstant.SELECT_SPEC_YES)){
				params.put("spec", go.getSpec());
				goodsSpec = goodsService.getGoodsSpecBySpec(params);
				if(goodsSpec != null){
					goodsSpecPro = goodsService.getGoodsSpecInfoBySpec(params);
					go.setPrice(DataUtil.getBigDecimal(goodsSpec.get("price")));
					go.setBidPrice(DataUtil.getBigDecimal(goodsSpec.get("bidPrice")));
					go.setRealPrice(DataUtil.getBigDecimal(goodsSpec.get("salesPrice")));
				
			}	
				go.getParams().put("goodsSpec",goodsSpec);
				go.getParams().put("goodsSpecPro",goodsSpecPro);
			}
			goodsN.add(go);
		}
	}
	
	public void removeByGoods(int goodsId,String spec,User user,HttpServletRequest request,
			HttpServletResponse response){
		//移除Cookie
		//reduceShopCartCookie(goodsId,spec,0,0, request, response);
		if(user != null){
		//数据库删除
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("goodsId", goodsId);
		params.put("userId", user.getId());
		params.put("spec", StringUtils.isEmpty(spec)?"0":spec);
		shoppingManager.delShoppingByGoodsId(params);
		}else{
			reduceShopCartCookie(goodsId,spec,0,0, request, response);
		}
	}
	
	@RequestMapping(value = "/addShopCartOne", method = { RequestMethod.POST })
	@ResponseBody
	public Map<String,Object> addShopCartOne(int goodsId,String spec,int buyNum, HttpServletRequest request,HttpSession session,
			HttpServletResponse response){
		this.logBefore(logger, "添加购物车");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
			spec = StringUtils.isEmpty(spec)?"0":spec;
		User user = (User)session.getAttribute("sessionUser");
		if(user != null){
		Map<String,Object> params = new HashMap<String, Object>();
		params.put("userId", user.getId());
		params.put("goodsId", goodsId);
		params.put("spec", spec);
		params.put("buyNum", buyNum);
		params.put("createTime", DateUtil.getTime());
		params.put("updateTime", DateUtil.getTime());
		List<Map<String, Object>> list = shoppingManager.getShoppingByAttr(params);
		if(list.size()==0){
			shoppingManager.addShopCart(params);
		}else {
			int num = (int) list.get(0).get("num");
			spec = (String) list.get(0).get("spec");
			buyNum = buyNum + num;
			updateBuyNum(goodsId,spec, buyNum, session,request,response);
		}
		}else{
			addShopCartCookie(goodsId, spec, buyNum, request, response);
		}
		
		resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "添加成功"));
		}catch(Exception e){
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		
		this.logAfter(logger);
		return resMap;
	}
	
	
	@RequestMapping(value = "/delShopCartOne", method = { RequestMethod.POST })
	@ResponseBody
	public Map<String,Object> delShopCartOne(int goodsId,String spec, HttpServletRequest request,HttpSession session,
			HttpServletResponse response){
		this.logBefore(logger, "删除购物车");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		User user = (User)session.getAttribute("sessionUser");
			spec = StringUtils.isEmpty(spec)?"0":spec;
			removeByGoods(goodsId,spec, user, request, response);
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "删除成功"));

		}catch(Exception e){
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		
		this.logAfter(logger);
		return resMap;
	}
	@RequestMapping(value = "/updateBuyNum", method = { RequestMethod.POST })
	@ResponseBody
	public void updateBuyNum(int goodsId,String spec,int buyNum,HttpSession session,HttpServletRequest request,HttpServletResponse response){
		this.logBefore(logger, "更新购买数量");
		try{
			User user = (User)session.getAttribute("sessionUser");
			spec = StringUtils.isEmpty(spec)?"0":spec;
			//reduceShopCartCookie(goodsId, spec, buyNum,1, request, response);
			if(user != null){
				Map<String,Object> params = new HashMap<String,Object>();
				params.put("goodsId", goodsId);
				params.put("spec", spec);
				params.put("userId", user.getId());
				params.put("buyNum", buyNum);
				params.put("updateTime", DateUtil.getTime());
				shoppingManager.updateShopBuyNum(params);
			}else{
				reduceShopCartCookie(goodsId, spec, buyNum,1, request, response);
			}
			
		}catch(Exception e){
			e.printStackTrace();
			this.logError(logger, e.getMessage());
		}
		
		
	}
	
	/**
	 * 商品加入
	 * @param goods
	 * @param spec
	 * @param buyNum
	 * @return
	 */
	public void addShopCartCookie(Integer goods,String spec,Integer buyNum,HttpServletRequest request,HttpServletResponse response){
		String goodsStr = null,reuslt = null,hltx_str=null;
		Cookie cook=null;
		
		 goodsStr = goods+":"+spec+":";
		 reuslt = goods+":"+spec+":"+buyNum;
		Cookie cookies[] = request.getCookies();
		if(cookies.length>=0){
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(CommonConstant.HLTX_SHOPCART_TICKET)) {
					cook = cookie;
					hltx_str = cookie.getValue();
					break;
				}
			}
			if(!StringUtils.isEmpty(hltx_str)){
				String[] tem=null;
				if(hltx_str.length()>0){
				tem = hltx_str.split("@");
				if(tem.length>=20){
					reuslt = "商品购买过多请清楚一些后再来购买";
				}else{
					 int indexOne = hltx_str.indexOf(goodsStr);
					 if(indexOne>=0){
							for (String str : tem) {
									//对数量进行加操作
									int index = str.indexOf(goodsStr);
									if(index >=0){
									String temps[] = str.split(":");
									String buyNums=temps[temps.length-1].trim();
									Integer buys =Integer.parseInt(buyNums);
									buys+=buyNum;
									reuslt = hltx_str.replace(str+"@", goodsStr+buys+"@");
									continue;
									}
							}
					 }else{
						 reuslt =hltx_str+reuslt+"@";
					 }
				}
				}
				cook.setValue(reuslt.trim());
			}else{
				reuslt +="@";
				cook= new Cookie(CommonConstant.HLTX_SHOPCART_TICKET, reuslt.trim());
			}
			}
		cook.setMaxAge(10 * 60 * 60 * 1000);
		cook.setPath("/"); 
		response.addCookie(cook);
	}
		
	
	/**
	 * 移除(减)商品
	 * @param goods
	 * @param spec
	 * @param buyNum
	 * @param state 操作类型（0删除 1修改）
	 * @param request
	 * @param reponse
	 */
	public void reduceShopCartCookie(Integer goodsId,String spec,Integer buyNum,Integer state,HttpServletRequest request,HttpServletResponse response){

		try{
		String goodsStr,goodsReg,reuslt=null,hltx_str=null;
		Cookie cook=null;
		goodsStr = goodsId+":"+spec+":";
		goodsReg = goodsStr+"(\\d+)@";
		Cookie cookies[] = request.getCookies();
		for (Cookie cookie : cookies) {
			if (cookie.getName().equals(CommonConstant.HLTX_SHOPCART_TICKET)) {
				cook = cookie;
				hltx_str = cookie.getValue();
				break;
			}
		}
		
		int index=hltx_str.indexOf(goodsStr);
		if(index >=0){
			if(state == 0){
			reuslt = hltx_str.replaceAll(goodsReg, "");
			}else{
			String newReuslt = 	goodsId+":"+spec+":"+buyNum+"@";
			reuslt = hltx_str.replaceAll(goodsReg, newReuslt);
			}
		}

		cook.setValue(reuslt);
		cook.setMaxAge(10 * 60 * 60 * 1000);
		cook.setPath("/"); 
		response.addCookie(cook);
		}catch(Exception e){
			this.logError(logger, e.getMessage());
		}
		
	}
	
	public void addCookie(String name, String value, HttpServletResponse reponse) {
		Cookie cookie = new Cookie(name.trim(), value.trim());
		cookie.setMaxAge(10 * 60 * 60 * 1000);// 设置为2个钟
		reponse.addCookie(cookie);
	}
	
	public void fixCookie(Cookie c, String value, HttpServletResponse reponse) {
		c.setValue(value.trim());
		c.setMaxAge(10 * 60 * 60 * 1000);// 设置为2个钟
		reponse.addCookie(c);
	}

	
	public static void main(String[] args) {
		String str ="make:a:b:";
		String sr[]= str.split(":");
		System.out.println(sr[0]);
	}
}
